<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryFormRef" :inline="true">
      <el-form-item prop="postCode" label="岗位编码">
        <el-input v-model="queryForm.postCode" placeholder="请输入岗位编码" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item prop="postName" label="岗位名称">
        <el-input v-model="queryForm.postName" placeholder="请输入岗位名称" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item prop="status" label="岗位状态">
        <el-select v-model="queryForm.status" placeholder="请选择岗位状态" :style="{ width: '181px' }">
          <el-option :value="2">正常</el-option>
          <el-option :value="1">停用</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-space>
          <el-button v-has="'admin:sysPost:query'" type="primary" @click="handleQuery" icon="Search"> 搜索</el-button>
          <el-button @click="handleResetQuery" icon="Refresh"> 重置</el-button>
        </el-space>
      </el-form-item>
    </el-form>

    <el-divider />

    <!-- action -->
    <div class="action">
      <el-space>
        <el-button v-has="'admin:sysPost:add'" type="primary" @click="handleAdd" icon="Plus">新增 </el-button>
        <el-button v-has="'admin:sysPost:remove'" type="primary" status="danger" @click="() => { deleteVisible = true; }"
          icon="Delete">批量删除 </el-button>
        <el-button type="primary" status="warning" disabled icon="Download">导出 </el-button>
      </el-space>
    </div>

    <el-table :data="tableData" row-key="postId">
      <el-table-column label='岗位编号' prop='postId'></el-table-column>
      <el-table-column label='岗位编码' prop='postCode'></el-table-column>
      <el-table-column label='岗位名称' prop='postName'></el-table-column>
      <el-table-column label='岗位排序' prop='sort'></el-table-column>
      <el-table-column label='状态' prop='status'>
        <template #default="scope">
          <el-tag v-if="scope.row.status == 2" type="success">正常</el-tag>
          <el-tag v-else type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label='创建时间' prop='createdAt'>
        <template #default="scope">
          {{ parseTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label='操作' prop='action'>
        <template #default="scope">
          <el-space>
            <el-button v-has="'admin:sysPost:edit'" text type="primary" @click="handleUpdate(scope.row)"
              icon="Edit">修改</el-button>
            <el-button v-has="'admin:sysPost:remove'" text type="primary"
              @click="() => { deleteVisible = true; deleteData = [scope.row.postId];  }" icon="Delete">删除</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :page-size="10" v-model="currentPage" layout="prev, pager, next" :total="pager.count"
      @current-change="handleQuery()" />

    <!-- Modal -->
    <el-dialog v-model="modalVisible" :title="modalTitle" title-align="start" @before-ok="handleSubmit"
      @close="() => {modalFormRef.resetFields(); }">
      <el-form :model="modalForm" :rules="rules" ref="modalFormRef">
        <el-form-item prop="postName" label="岗位名称">
          <el-input v-model="modalForm.postName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item prop="postCode" label="岗位编码">
          <el-input v-model="modalForm.postCode" placeholder="请输入岗位编码" />
        </el-form-item>
        <el-form-item prop="sort" label="岗位排序">
          <el-input-number v-model="modalForm.sort" mode="button" :default-value="0" :style="{ width: '150px' }" />
        </el-form-item>
        <el-form-item prop="status" label="岗位状态">
          <el-radio-group v-model="modalForm.status">
            <el-radio :label="2"> 正常 </el-radio>
            <el-radio :label="1"> 停用 </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input type='textarea' v-model="modalForm.remark" placeholder="请输入备注内容" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-row justify="end">
          <el-button @click="modalFormRef.resetFields();modalVisible=false;">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </el-row>
      </template>
    </el-dialog>

    <!-- Akiraka 20230223 删除与批量删除 开始 -->
    <DeleteModal :data="deleteData" :visible="deleteVisible" :apiDelete="removePost"
      @deleteVisibleChange="() => deleteVisible = false" />
    <!-- Akiraka 20230223 删除与批量删除 结束 -->
  </div>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue';
import { getPost, addPost, removePost, updatePost } from '@/api/admin/post';
import { parseTime } from '@/utils/parseTime';
import PageTable from '@/components/Table/PageTable.vue'


// Akiraka 20230210 删除数据
const deleteData = ref([])
// Akiraka 20230210 删除对话框
const deleteVisible = ref(false)
// Akiraka 20230210 监听删除事件
const modalFormRef = ref({});
watch(() => deleteVisible.value ,(value) => {
  if ( value == false ) {
    getPostInfo(pager);
  }
})

const { proxy } = getCurrentInstance();

const currentPage = ref(1);
// Pager
const pager = {
  count: 0,
  pageIndex: 1,
  pageSize: 10,
};
// form
const queryForm = reactive({});
const modalForm = reactive({
  sort: 0,
  status: 2,
});

// Rules
const rules = {
  postName: [{ required: true, message: '请输入岗位名称' }],
  postCode: [{ required: true, message: '请输入岗位编码' }],
  sort: [{ required: true, message: '请选择岗位排序' }],
};

// Modal
const modalVisible = ref(false);
const modalTitle = ref('默认标题');
const queryFormRef = ref({});

// Batch Del List
let batchList = [];

// Table Data
const tableData = ref([]);

// 新增
const handleAdd = () => {
  modalVisible.value = true;
  modalTitle.value = '新增岗位';
};

// 修改
const handleUpdate = async (record) => {
  modalVisible.value = true;
  modalTitle.value = '修改岗位';

  await nextTick();
  Object.assign(modalForm, record);
};

// Modal ok
// 异步关闭Modal需要调用 done()
const handleSubmit = (done) => {
  modalFormRef.value.validate(async (valid) => {
    if (valid) {
      let res;
      if (!modalForm.postId) {
        const { code, msg } = await addPost(modalForm);
        if (code == 200 ) {
          proxy.$message.success('新增成功');
        } else {
          proxy.$message.error(msg);
        }
      } else {
        const { code, msg } = await updatePost(modalForm, modalForm.postId);
        if (code == 200 ) {
          proxy.$message.success('更新成功');
        } else {
          proxy.$message.error(msg);
        }
      }
      done();
      getPostInfo(pager);
    } else {
      proxy.$message.error('表单校验失败');
      done(false);
    }
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (batchList.length !== 0) {
    proxy.$modal.warning({
      title: '提示',
      content: '是否批量删除以下选中的数据？',
      hideCancel: false,
      onOk: async () => {
        const res = await removePost({ ids: batchList });
        proxy.$message.success(res.msg);
        getPostInfo(pager);
      },
      onCancel: () => {
        proxy.$message.info('已取消批量删除数据');
      },
    });
  } else {
    proxy.$message.error('请勾选需要删除的数据！');
  }
};

/**
 * 分页改变
 * @param {Number} [page]
 */
 const handlePageChange = (page) => {
  pager.pageIndex = page;

  // 修改当前页码
  currentPage.value = page;
  getPostInfo({ ...pager, ...queryForm });
};

// 每页数据量
const handlePageSizeChange = (pageSize) => {
  pager.pageSize = pageSize;
  getPostInfo({ ...pager, ...queryForm });
};

// 获取岗位信息
const getPostInfo = async (params = {}) => {
  const { data, code, msg } = await getPost(params);
  if ( code == 200 ) {
    tableData.value = data.list;
    Object.assign(pager, { count: data.count, pageIndex: data.pageIndex, pageSize: data.pageSize });
  } else {
    proxy.$message.error(msg);
  }
};

// 查询岗位信息
const handleQuery = async () => {
  const params = {
    pageIndex: pager.pageIndex,
    pageSize: pager.pageSize,
    ...queryForm,
  };

  getPostInfo(params);
};

// 重置搜索
const handleResetQuery = () => {
  queryFormRef.value.resetFields();

  getPostInfo(queryForm);
}

onMounted(async () => {
  getPostInfo(pager);
});
</script>

<style lang="scss">
.action {
  margin-bottom: 12px;
}
</style>
